package com.gengzp.mq.server.job;

import com.gengzp.mq.common.model.entity.GengzpMqMessage;
import com.gengzp.mq.common.utils.GengzpMqDateUtils;
import com.gengzp.mq.server.facade.IGengzpMqFacadeService;
import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;

import static com.gengzp.mq.common.constants.GengzpMqDateFormatConstants.YMD_HMS;

/**
 * @ClassName ClearMessageJob
 * @Description 消息表清理任务
 * @Author gengzp
 * @Date 2025/6/8 22:37
 */
@Component
public class ClearMessageJob {

    private static final Logger logger = LoggerFactory.getLogger(ClearMessageJob.class);

    @Autowired
    private IGengzpMqFacadeService gengzpMqFacadeService;

    /**
     * 消息表清理任务
     * 定时将数据库中的消息进行清空, 防止表中的数据过于冗余
     * 每24小时扫描一次
     */
    @Scheduled(fixedRate = 24 * 60 * 60 * 1000)
    public void execute() {
        // 当前系统时间
        Date startDate = new Date();
        logger.info("===================== 定时任务 [消息表历史数据清理] 开始, 当前时间: [{}] =====================",
                GengzpMqDateUtils.Date2String(startDate, YMD_HMS));
        doExecute(startDate);
        logger.info("===================== 定时任务 [消息表历史数据清理] 完成, 本次耗时: [{}ms] =====================",
                new Date().getTime() - startDate.getTime());
    }

    /**
     * 任务处理逻辑
     *
     * @param startDate 开始时间
     */
    private void doExecute(Date startDate) {
        // 查询超过7天的消息集合
        List<GengzpMqMessage> messages = gengzpMqFacadeService.searchTimeoutMessageByCreatedTime(
                new Date((new Date()).getTime() - 7 * 24 * 60 * 60 * 1000));
        if (CollectionUtils.isEmpty(messages)) {
            return;
        }

        // 过滤出超过7天的消息
        List<GengzpMqMessage> overtimeMessages = messages.stream()
                .filter(v -> checkIsOvertime(v.getCreatedTime(), startDate)).toList();
        if (CollectionUtils.isEmpty(overtimeMessages)) {
            return;
        }

        // 从数据库中将这些消息物理删除
        gengzpMqFacadeService.batchDeleteMessage(
                overtimeMessages.stream().map(GengzpMqMessage::getId).toList());
    }

    private boolean checkIsOvertime(Date createdTime, Date currentTime) {
        return currentTime.getTime() - createdTime.getTime() > 7 * 24 * 60 * 60 * 1000;
    }

}
